//
//  MXShiftInController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/5.
//

#import "MXShiftInController.h"
#import "MxPublicNav.h"
#import "MXShiftInlListCell.h"
#import "DCAlterView.h"
#import "MXHomeEquimentListController.h"
#import "MXHomeModel.h"

@interface MXShiftInController () <MxNavigationViewDelegate,UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView         *listTab;
@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic, strong) UILabel *enterLab;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) UILabel *selectLab;
@property (nonatomic, assign) BOOL selectAll;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (nonatomic, strong) NSMutableArray *listArray;
@end

@implementation MXShiftInController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"];
    self.selectArray = [[NSMutableArray alloc] init];
    self.listArray = [[NSMutableArray alloc] init];
    self.selectIndex = -1;
    [self createUI];
    [self getCanTransDevice];
}

- (void)getCanTransDevice {
    MJWeakSelf
    NSString *urlStr = [NSString stringWithFormat:@"api/app/family/canTransfer?currentFamilyId=%@",SAFEPARAMETER(self.hModel.familyId)];
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            
            [weakSelf.listArray removeAllObjects];
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXHomeModel class] json:dict[@"data"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            [weakSelf.listTab reloadData];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)createUI {
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = @"移入设备";
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    
    MJWeakSelf
    self.selectLab = [[UILabel alloc] init];
    self.selectLab.text = @"全选";
    self.selectLab.userInteractionEnabled = YES;
    self.selectLab.textColor = [UIColor dc_colorWithHexString:@"#000000"];
    self.selectLab.font = PFRFontMedium(15);
    [self.selectLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapSelectAll];
    }]];
    [self.nav addSubview:self.selectLab];
    [self.selectLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-24);
        make.centerY.mas_equalTo(self.nav.titleLab);
    }];
    
    UILabel *noticleLab = [[UILabel alloc] init];
    noticleLab.text = [NSString stringWithFormat:@"请选择要移入到“%@”的设备",SAFEPARAMETER(self.hModel.familyName)];
    [self.view addSubview:noticleLab];
    noticleLab.font = PFRFontMedium(14);
    noticleLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.9];
    [noticleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.top.offset(kNavBarHeight + 23);
    }];
    
    self.enterLab = [[UILabel alloc] init];
    self.enterLab.textAlignment = NSTextAlignmentCenter;
    self.enterLab.text = @"确定";
    self.enterLab.textColor = [UIColor colorWithHexString:@"#FEFEFE"];
    self.enterLab.font = PFRFontMedium(16);
    self.enterLab.backgroundColor = [UIColor dc_colorWithHexString:@"#3278F6" alpha:0.5];
    self.enterLab.layer.cornerRadius = 24;
    self.enterLab.layer.masksToBounds = YES;
    [self.enterLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf shiftIn];
    }]];
    [self.view addSubview:self.enterLab];
    [self.enterLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(48);
        make.bottom.offset(-48);
        make.left.offset(15);
        make.right.offset(-15);
    }];
    
    [self.view addSubview:self.listTab];
    [self.listTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.mas_equalTo(noticleLab.mas_bottom).offset(15);
        make.bottom.mas_equalTo(self.enterLab.mas_top).offset(-5);
    }];
    
}


#pragma mark - ________ UITableView ________

- (UITableView *)listTab {
    
    if (nil == _listTab) {
        _listTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _listTab.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"];
        _listTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTab.delegate = self;
        _listTab.dataSource = self;
        _listTab.rowHeight = 80.0;
        _listTab.showsVerticalScrollIndicator = NO;
        _listTab.showsHorizontalScrollIndicator= NO;
        [_listTab registerClass:[MXShiftInlListCell class] forCellReuseIdentifier:NSStringFromClass([MXShiftInlListCell class])];
        if (@available(iOS 11.0, *)) {
            _listTab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _listTab.sectionHeaderTopPadding = 0;
        }
    }
    return _listTab;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MXHomeModel *model = self.listArray[indexPath.section];
    MXHomeListModel *listModel = model.deviceList[indexPath.row];
    MXShiftInlListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MXShiftInlListCell class])];
    [cell reloadCellWithModel:listModel];
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MXHomeModel *model = self.listArray[section];
    return model.deviceList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectIndex = indexPath.row;
    NSString *index = [NSString stringWithFormat:@"%ld",indexPath.row];
    MXHomeModel *model = self.listArray[indexPath.section];
    MXHomeListModel *listModel = model.deviceList[indexPath.row];
    listModel.select = !listModel.select;
    if ([self.selectArray containsObject:listModel.ID]) {
        [self.selectArray removeObject:listModel.ID];
    } else {
        [self.selectArray addObject:listModel.ID];
    }
    [self.listTab reloadData];
    [self judgeBtnState];
}

- (void)judgeBtnState {
    
    if (self.selectArray.count > 0) {
        self.enterLab.userInteractionEnabled = YES;
        self.enterLab.backgroundColor = [UIColor dc_colorWithHexString:@"#3278F6"];
    } else {
        self.enterLab.userInteractionEnabled = NO;
        self.enterLab.backgroundColor = [UIColor dc_colorWithHexString:@"#3278F6" alpha:0.5];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    MXHomeModel *model = self.listArray[section];
    return model.familyName;
}


- (void)shiftIn {
    
    MJWeakSelf
    
    DCAlterView * alterView = [[DCAlterView alloc] initWithTitle:@"" content:[NSString stringWithFormat:@"确认将设备移入到“%@”？",SAFEPARAMETER(self.hModel.familyName)]];
    [alterView addActionWithTitle:@"取消" color:[UIColor dc_colorWithHexString:@"#000000" alpha:0.5] type:DCAlterTypeCancel halderBlock:^(UIButton *button) {
            
    }];
    [alterView addActionWithTitle:@"确认" color:[UIColor colorWithHexString:@"#3278F6"] type:DCAlterTypeDone halderBlock:^(UIButton *button) {
        [weakSelf gotoEuipmentList];
    }];
    
    [DC_KeyWindow addSubview:alterView];
    [alterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(DC_KeyWindow);
    }];
}

- (void)gotoEuipmentList {
    NSString *deviceId = [self.selectArray componentsJoinedByString:@","];
    MXHomeModel *model = self.listArray[0];
    NSString *outFamily = model.familyId;
    NSString *urlStr = [NSString stringWithFormat:@"%@?deviceId=%@&inFamily=%@&outFamily=%@",@"api/app/device/transfer",deviceId,self.hModel.familyId,outFamily];

    MJWeakSelf
    [self.view makeToastActivity];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"transferdevice" object:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
//    deviceId
//  设备id
//  query
//  true
//  integer
//         inFamily
//  移入设备的家庭id
//  query
//  true
//  integer
//         outFamily
//    MXHomeEquimentListController *listVc = [[MXHomeEquimentListController alloc] init];
//    [self.navigationController pushViewController:listVc animated:YES];
}

- (void)tapSelectAll {
    self.selectAll = !self.selectAll;
    if (self.selectAll) {
        [self.selectArray removeAllObjects];
        self.selectLab.text = @"全不选";
        for (int i = 0; i <self.listArray.count; i++) {
            MXHomeModel *model = self.listArray[i];
            for (int j = 0; j < model.deviceList.count; j++) {
                MXHomeListModel *listModel = model.deviceList[j];
                listModel.select = YES;
                [self.selectArray addObject:listModel.ID];
            }
        }
    } else {
        self.selectLab.text = @"全选";
        [self.selectArray removeAllObjects];
        for (int i = 0; i <self.listArray.count; i++) {
            MXHomeModel *model = self.listArray[i];
            for (int j = 0; j < model.deviceList.count; j++) {
                MXHomeListModel *listModel = model.deviceList[j];
                listModel.select = NO;
            }
        }
    }
    [self.listTab reloadData];
    [self judgeBtnState];
}

-(void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

@end
